if ("EventSource" in window) {
  new EventSource("/esbuild").addEventListener("change", (e) => {
    const { added, removed, updated } = /**
     * @type {{ added: string[], removed: string[], updated: string[] }}
     */ (JSON.parse(e.data));

    if (!added.length && !removed.length && updated.length === 1) {
      /**
       * @type {HTMLCollectionOf<HTMLLinkElement>}
       */
      const links = document.getElementsByTagName("link");
      if (!links) return;
      for (const link of links) {
        const url = new URL(link.href, import.meta.url);

        if (url.host === location.host && url.pathname === updated[0]) {
          const next = /** @type {HTMLLinkElement} */ (link.cloneNode());
          // add resourceQuery
          next.href = `${updated[0]}?${Math.random().toString(36).slice(2)}`;
          next.onload = () => link.remove();
          link.parentNode?.insertBefore(next, link.nextSibling);
          return;
        }
      }
    }

    // reload only
    location.reload();
  });
}
